<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<style>
			#p-purchase-createForm .form-item{margin: 20px 0px;}
			#p-purchase-createForm .form-item > label{min-width: 72px; text-align: left; display: inline-block;}
			.no-scroller{overflow-y: hidden;}
			
			#create-purchaseProductForm{padding-bottom: 50px;}
			#create-purchaseForm{background: aliceblue;}
			.purchase-form-table , .purchaseProduct-form-table{table-layout: fixed;}
			.purchase-form-table > tbody > tr , .purchaseProduct-form-table > tbody > tr{height: 36px;}
			.purchase-form-table > tbody > tr > td:first-child ,.purchaseProduct-form-table > tbody > tr > td:first-child{width: 100px; text-align: right; padding-right: 10px;}
			.purchase-form-table > tbody > tr > td:last-child , .purchaseProduct-form-table > tbody > tr > td:last-child{width: 200px;}
			.purchase-form-table > tbody > tr > td:last-child > input , .purchaseProduct-form-table > tbody > tr > td:last-child > input{width: 100%; height: 30px; line-height: 30px; border: 1px solid #D3D3D3; border-radius: 2px; box-sizing: border-box; padding: 0px 8px;}
			.purchase-form-table > tbody > tr > td:last-child > textarea{width: 100%; height: 50px; border: 1px solid #D3D3D3; border-radius: 2px; resize: none; box-sizing: border-box; padding: 0px 8px;}
			.purchaseProduct-form-table > tbody > tr > td > img{width: 60px;}
		</style>
		<div class="super-theme-example">
			<div class="options-toolbar">
				<form id="ppurchaseDatagridQueryParams">
					<input id="p-purchase-combo" name="pendingPurchaseCode" style="width:240px;">
					<input class="easyui-textbox" name="productId" data-options="width:120,prompt:'产品ID'">
					<input class="easyui-textbox" name="productSkuBarcode" data-options="width:120,prompt:'产品SKU编码'">
					<input id="p-purchase-supplier-combo" name="supplierId" style="width:200px;">
					<a href="javascript:void(0)" class="easyui-linkbutton primary" data-options="iconCls:'fa fa-search'" onclick="p_purchase.methods.queryDatagrid();">查询</a>
				</form>
				<div class="top-options">
					<a href="javascript:void(0)" class="easyui-menubutton info" data-options="menu:'#p_purchase_list_tools'">操作</a>
					<div id="p_purchase_list_tools" style="width:120px;">
						<div data-options="iconCls:'fa fa-cart-plus'" onclick="p_purchase.purchase.open()">采购</div>
						<div data-options="iconCls:'fa fa-plus'" onclick="p_purchase.methods.createPPurchase()">新建缺货单</div>
						<div data-options="iconCls:'fa fa-edit'" onclick="p_purchase.purchase.pPurchasePurchased()">设置为已采购</div>
						<div data-options="iconCls:'fa fa-download'" onclick="exportExcel(commonConfig.mgUrlPrefix() + '/admin/p-purchase/products/export' , p_purchase.methods.initDatagridQueryParams())()">下载缺货单</div>
					</div>
				</div>
			</div>
			<table id="p-purchase-datagrid"></table>
			<div id="p-purchase-createWin" class="easyui-window" title="生成缺货单" style="width:380px;height:220px" data-options="modal:true,closed:true,minimizable:false,maximizable:false">
				<div class="super-theme-example">
					<form id="p-purchase-createForm">
						<div class="form-item">
							<label for="" class="label-top">仓库：</label>
							<input id="p-purchase-create-storehouseCombo" name="storehouseId" style="width:260px;">
						</div>
					</form>
					<div style="text-align: right; box-sizing: border-box;padding: 10px;">
						<a href="#" class="easyui-linkbutton" style="width: 80px;" onclick="$('#p-purchase-createWin').window('close');">取消</a>
						<a href="#" class="easyui-linkbutton primary" style="width: 80px;" onclick="p_purchase.methods.createPPurchaseSubmit();">保存</a>
					</div>
				</div>
			</div>
			<!-- 散采入口 -->
			<div id="createPurchaseWin" class="easyui-window" title="采购" data-options="modal:true,fit:true,closed:true,minimizable:false,maximizable:false,tools:[{iconCls: 'fa fa-shopping-cart', handler: p_purchase.purchase.openCart}, {iconCls: 'fa fa-list-alt', handler: p_purchase.purchase.openOrderList}]">
			    <div class="easyui-layout" data-options="fit:true">
					<div data-options="region:'east'" style="width:350px">
						<form id="create-purchaseForm">
							<table class="purchase-form-table" cellpadding="5">
								<tr>
					    			<td>采购仓库:</td>
					    			<td><input id="ppurchase-create-storehouseCombo" name="storehouseId" style="width: 200px;"></td>
					    		</tr>
					    		<tr>
					    			<td>采购单号:</td>
					    			<td><input type="text" name="purchaseCode" placeholder="采购单号..."></input></td>
					    		</tr>
					    		<tr>
					    			<td>供应商名称:</td>
					    			<td><input type="text" name="supplierName" placeholder="供应商名称..."></input></td>
					    		</tr>
					    		<tr>
					    			<td>供应商网址:</td>
					    			<td><input type="text" name="purchaseUrl" placeholder="供应商网址..."></input></td>
					    		</tr>
					    		<tr>
					    			<td>采购总价:</td>
					    			<td><input type="text" name="purchasePrice" placeholder="采购总价..."></input></td>
					    		</tr>
					    		<tr>
					    			<td>运费:</td>
					    			<td><input type="text" name="purchaseFreightPrice" placeholder="运费..."></input></td>
					    		</tr>
					    		<tr>
					    			<td>采购备注:</td>
					    			<td><textarea type="text" name="comments" placeholder="采购备注..."></textarea></td>
					    		</tr>
					    	</table>
						</form>
						<hr />
						<div id="create-purchaseProductForm"></div>
						
						<a href="#" class="easyui-linkbutton primary" data-options="iconCls:'fa fa-save'" style="width:100%; position: absolute; bottom: 0px;" onclick="p_purchase.purchase.savePurchase();">提交</a>
					</div>
					<div data-options="region:'center'">
						<div id="purchaseTabInfo" class="easyui-tabs" data-options="fit:true,border:false"></div>
					</div>
			    </div>
			</div>
		</div>
		<script type="text/javascript">
			var p_purchase = {
				datas : {
					currentPpurchase: null ,
					color: {
	                	bgColor : ['azure' , 'beige' , 'bisque'],
	                	bgColorIndex : 0,
	                	currentRow : {}
	                }
				},
				purchase: {
					open: function(){
						var _checkeds = $('#p-purchase-datagrid').datagrid('getChecked');
						if(_checkeds.length == 0){
							showMessage('没有选择要采购的商品...');
							 return;
						}
						var _supplierIds = [] ; 
						$.each(_checkeds, function(index , _checked) {
							if($.inArray(_checked.supplierId , _supplierIds) == -1)_supplierIds.push(_checked.supplierId);
						});
						if(_supplierIds.length > 1){
							showMessage('仅支持单供应商采购...');
							 return;
						}
						p_purchase.datas.purchaseList = _checkeds ; 
						
						$('#ppurchase-create-storehouseCombo').combobox({
						    url: commonConfig.mgUrlPrefix() + '/admin/storehouse/combo',
						    valueField: 'id',
						    textField: 'text',
						    onLoadSuccess: function(){
								$('#ppurchase-create-storehouseCombo').combobox('select' , p_purchase.datas.currentPpurchase.attribute);
						    }
						});
						
						$('#createPurchaseWin').window('open');
						var _length = $('#purchaseTabInfo ul.tabs > li').length;
						for(var i = _length ; i > 0 ; i--){
							$('#purchaseTabInfo').tabs('close' , (i-1));
						}
						
						$('#create-purchaseForm').form('clear');
						
						var _one = p_purchase.datas.purchaseList[0];
						$('#create-purchaseForm').form('load' , {supplierName: _one.supplierName});
						
						var _purchaseProductHtml = '' ; 
						$.each(p_purchase.datas.purchaseList, function(index , product) {
							p_purchase.purchase.addTab(product.productTitle + '=>' + product.productSkuName , product.sourceUrl);
							_purchaseProductHtml += '<form><table class="purchaseProduct-form-table" cellpadding="5">'+
													'<tr style="display: none;">'+
													'	<td>商品ID:</td>'+
													'	<td><input type="text" name="productId" value="'+ product.productId +'" placeholder="商品ID..."></input></td>'+
													'</tr>'+
													'<tr>'+
													'	<td>商品标题:</td>'+
													'	<td><input type="text" name="productTitle" value="'+ product.productTitle +'" placeholder="商品标题..." readonly="readonly"></input></td>'+
													'</tr>'+
													'<tr style="display: none;">'+
													'	<td>SKUID:</td>'+
													'	<td><input type="text" name="productSkuId" value="'+ product.productSkuId +'" placeholder="SKUID..."></input></td>'+
													'</tr>'+
													'<tr>'+
													'	<td>商品规格:</td>'+
													'	<td><input type="text" name="productSkuName" value="'+ product.productSkuName +'" placeholder="商品规格..." readonly="readonly"></input></td>'+
													'</tr>'+
													'<tr>'+
													'	<td>商品编码:</td>'+
													'	<td><input type="text" name="productSkuBarcode" value="'+ product.productSkuBarcode +'" placeholder="商品编码..." readonly="readonly"></input></td>'+
													'</tr>'+
													'<tr>'+
													'	<td>商品图片:</td>'+
													'	<td><img src="'+ product.productSkuImage +'"></td>'+
													'</tr>'+
													'<tr style="display: none;">'+
													'	<td>商品图片:</td>'+
													'	<td><input type="text" name="productSkuImage" value="'+ product.productSkuImage +'" placeholder="商品图片..."></input></td>'+
													'</tr>'+
													'<tr>'+
													'	<td>采购价:</td>'+
													'	<td><input type="text" name="purchasedPrice" value="'+ product.referencePurchasePrice +'" placeholder="采购价..."></input></td>'+
													'</tr>'+
													'<tr>'+
													'	<td>采购数量:</td>'+
													'	<td><input type="text" name="purchasedQuantity" value="'+ product.quantity +'" placeholder="采购数量..."></input></td>'+
													'</tr>'+
													'</table></form>';
							_purchaseProductHtml += '<hr/>';
						});
						$('#create-purchaseProductForm').html(_purchaseProductHtml);
					},
					openCart: function(){
						var _sourceUrl = p_purchase.datas.purchaseList[0].sourceUrl;
						if(_sourceUrl.indexOf('taobao') > 0){
							p_purchase.purchase.addTab('购物车' , 'https://cart.taobao.com/cart.htm');
						}else if(_sourceUrl.indexOf('tmall') > 0){
							p_purchase.purchase.addTab('购物车' , 'https://cart.tmall.com/cart.htm');
						}else if(_sourceUrl.indexOf('1688') > 0){
							p_purchase.purchase.addTab('购物车' , 'https://cart.1688.com/cart.htm');
						}
					},
					openOrderList: function(){
						var _sourceUrl = p_purchase.datas.purchaseList[0].sourceUrl;
						if(_sourceUrl.indexOf('taobao') > 0 || _sourceUrl.indexOf('tmall') > 0){
							p_purchase.purchase.addTab('购物车' , 'https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm');
						}else if(_sourceUrl.indexOf('1688') > 0){
							p_purchase.purchase.addTab('购物车' , 'https://work.1688.com/?_path_=buyer2017Base/2017buyerbase_trade/buyList');
						}
					},
					addTab: function(_title , _url){
						$('#purchaseTabInfo').tabs('add',{
							title: _title,
							content: '<iframe frameborder="0" style="width: 100%; height: 100%; border: none; overflow: hidden;" src="' + _url + '"></iframe>',
							bodyCls: 'no-scroller',
							closable: true
						});
					},
					pPurchasePurchased: function(){
						var _checkeds = $('#p-purchase-datagrid').datagrid('getChecked');
						if(_checkeds.length == 0){
							showMessage('没有选择要设置的商品...');
							return;
						}
						$.messager.confirm('提示', '确定批量设置为已采购?', function(r){
							if (r){
								var pendingPurchaseCode = $('#p-purchase-combo').combobox('getValue')
								var params = []
								_checkeds.map((e)=>{
									params.push({
										pendingPurchaseCode: pendingPurchaseCode,
										productSkuBarcode: e.productSkuBarcode
									})
								})
								requestBodyServer(commonConfig.mgUrlPrefix() + '/admin/p-purchase/purchased', 'PUT', params).then((response) => {
									if (response.code == 1) {
										showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
										p_purchase.methods.queryDatagrid();
									}else {
										$.messager.alert('提示',response.message,'error');
									}
								}).catch((error) => {
									console.log(error)
								});
							}
						});
					},
					savePurchase: function(){
						var _purchaseForm = $('#create-purchaseForm').serializeJson();
						var purchaseCreateRequest = {
							storehouseId: _purchaseForm.storehouseId,
							supplierName: _purchaseForm.supplierName,
							purchaseCode: _purchaseForm.purchaseCode, 
							purchaseUrl: _purchaseForm.purchaseUrl, 
							purchasePrice: _purchaseForm.purchasePrice, 
							purchaseFreightPrice: _purchaseForm.purchaseFreightPrice, 
							comments: _purchaseForm.comments, 
							purchaseProductCreateRequests: []
						};
						$('#create-purchaseProductForm form').each(function(i){
							purchaseCreateRequest.purchaseProductCreateRequests.push($('#create-purchaseProductForm form').eq(i).serializeJson());
						});
						
						requestBodyServer(commonConfig.mgUrlPrefix() + '/admin/purchase/create' , 'POST', [purchaseCreateRequest]).then((response) => {
							if (response.code == 1) {
								//在这里需要注意操作的情况
								$('#createPurchaseWin').window('close');
								if(response.datas && response.datas.length > 0){
									showErrorMsgs(response.datas , [[{field:'purchaseCode',title:'采购单号',width:60,align:'center'},{field:'errorMsg',title:'错误信息',width:60,align:'center'}]]);
								}else{
									showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
									$('#p-purchase-datagrid').datagrid('reload');
								}
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					}
				},
				methods: {
					initToobarCombo: function(){
						$('#p-purchase-combo').combobox({
						    url: commonConfig.mgUrlPrefix() + '/admin/p-purchase/combo',
						    valueField: 'id',
						    textField: 'text',
						    onLoadSuccess: function(){
						    	var _datas = $('#p-purchase-combo').combobox('getData');
								if(_datas.length > 0)$('#p-purchase-combo').combobox('select' , _datas[0].id);
								p_purchase.methods.initDatagrid();
						    },
						    onSelect: function(record){
						    	p_purchase.datas.currentPpurchase = record ; 
						    }
						});
						$('#p-purchase-supplier-combo').combobox({
						    url: commonConfig.shopUrlPrefix() + '/supplier/combobox',
						    valueField: 'id',
						    textField: 'text'
						});
					},
					initDatagrid: function(){
						$('#p-purchase-datagrid').datagrid({
							height: $(document).height() - 200,
						    url: commonConfig.mgUrlPrefix() + '/admin/p-purchase/products',
						    queryParams: {
								pendingPurchaseCode: $('#p-purchase-combo').combobox('getValue')
							},
							rowStyler: function(index,row){
								return 'background-color:'+ row.bgColor +';';
							},
							loadFilter: function(data){
								$.each(data.datas.content, function(index, _data) {
			                		var _currentRow = p_purchase.datas.color.currentRow;
			                		if(_data.supplierId == _currentRow.supplierId){
			            					_data['bgColor'] = _currentRow['bgColor'];
			        				}else{
			        					p_purchase.datas.color.currentRow = _data;
			        					p_purchase.datas.color.currentRow['bgColor'] = p_purchase.datas.color.bgColor[p_purchase.datas.color.bgColorIndex];
			        					p_purchase.datas.color.bgColorIndex = (p_purchase.datas.color.bgColorIndex + 1) % 3;
			        				}
			                	});
								return {total: data.datas.totalElements,rows: data.datas.content};
							},
						    columns:[[
						    	{field:'ck',checkbox:true,width:50,align:'center'},
								{field:'productId',title:'产品ID',width:60,align:'center'},
								{field:'productTitle',title:'产品名称',width:120,align:'center'},
								{field:'productSkuBarcode',title:'SKU编码',width:80,align:'center'},
								{field:'productSkuName',title:'规格名称',width:100,align:'center'},
								{field:'productSkuImage',title:'图片',width:100,align:'center',formatter:function(value,row,index){return '<img class="td-img" src="'+ value +'">';}},
								{field:'quantity',title:'数量',width:60,align:'center'},
								{field:'referencePurchasePrice',title:'参考价',width:60,align:'center'},
								{field:'sourceNumber',title:'货号',width:80,align:'center'},
								{field:'supplierName',title:'供应商',width:100,align:'center' ,formatter:function(value,row,index){return '<a href="'+ row.sourceUrl +'" target=_blank>'+ value +'</a>';}},
						    ]]
						});
					},
					initDatagridQueryParams: function(){
						var params = $('#ppurchaseDatagridQueryParams').serializeArray();
						var queryParams = {};
						$.each(params , function(index , param){
						     queryParams[param.name] = param.value;
						})
						return queryParams;
					},
					queryDatagrid: function(){
						$('#p-purchase-datagrid').datagrid('reload',p_purchase.methods.initDatagridQueryParams());
					},
					createPPurchase: function(){
						$('#p-purchase-createWin').window('open');
						$('#p-purchase-create-storehouseCombo').combobox({
						    url: commonConfig.mgUrlPrefix() + '/admin/storehouse/combo',
						    valueField: 'id',
						    textField: 'text',
						    onLoadSuccess: function(){
						    	var _datas = $('#p-purchase-create-storehouseCombo').combobox('getData');
								if(_datas.length > 0)$('#p-purchase-create-storehouseCombo').combobox('select' , _datas[0].id);
						    }
						});
						
					},
					createPPurchaseSubmit: function(){
						var _datas = $('#p-purchase-create-storehouseCombo').combobox('getData');
						var selectValue = $('#p-purchase-create-storehouseCombo').combobox('getValue');
						var _select = null ; 
						$.each(_datas, function(index , _data) {
							if(_data['id'] == selectValue){
								_select = _data ; 
								return false;
							}
						});
						if(_select){
							requestBodyServer(commonConfig.mgUrlPrefix() + '/admin/p-purchase/create' , 'POST', {storehouseId: _select.id , storehouseName: _select.text}).then((response) => {
								if (response.code == 1) {
									showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
									$('#p-purchase-createWin').window('close');
									//p_purchase.methods.queryDatagrid();
									$('#p-purchase-combo').combobox('reload');
								}else {
									$.messager.alert('提示',response.message,'error');
								}
							}).catch((error) => {
								console.log(error)
							});
						}else{
							$.messager.alert('提示','没有选择仓库','error');
						}
					}
				},
				init : function(){
					p_purchase.methods.initToobarCombo();
				}
			}
			p_purchase.init();
		</script>
	</body>
</html>
